var db = require('../conf/db')
var fs = require('fs')

const jwtUtil = require('../public/utils/jwt')
    // const baseUrl='localhost:2077/'
const baseUrl = 'localhost:2077/images/'
    //base64上传头像图片
const uploadPic = async(req, res) => {
let jwt = new jwtUtil()

        let user = jwt.verifyToken(req.headers['x-token'])
        let data = req.body.base64
            //将前台传来的base64数据去掉前缀
        var imgData = data.replace(/^data:image\/\w+;base64,/, '');

        var dataBuffer = new Buffer.from(imgData, 'base64');
        //写入文件
        fs.writeFile('./public/images/' + user.data.loginName + '-' + req.body.fileName + '.png', dataBuffer, function(err) {
            if (err) {
                res.send(err);
            } else {
                let avatar="http://"+ baseUrl + user.data.loginName+ '-' + req.body.fileName+ ".png"
                let sql = 'UPDATE `mdm`.`user` SET `avatar` ="' + avatar + '" WHERE `loginName` = "' + user.data.loginName + '"'
                db.query(sql, [], function(results, fields) {
                    // 以json的形式返回
                    res.send({ code: 20000, data: {avatar:avatar+"?"+new Date().getTime()}, message: '修改成功' })
                })

            }
        });
        // 以json的形式返回
        // res.send({ code: 20000, data: {} })
    }
const delFile = async(req, res) => {
   //接收文件名的参数
  let {file} = req.query
  console.log(file)

  //删除 static 目录下的该文件
  fs.unlink(`./public/images/${file}`, function(err){
    console.log(err)
    res.send({code:20000})
    // res.redirect('/')
  })
}
module.exports = {
    uploadPic,
    delFile
}